//
//  UITableViewController+HDMyCommunityController.m
//  app
//
//  Created by D on 15/8/20.
//  Copyright (c) 2015年 hdaren. All rights reserved.
//

#import "HDMyCommunityController.h"
#import "HDCommunityManager.h"
#import "HDCommunityResult.h"
#import "HDMyCommunityCell.h"
#import "HDMyCommunityModel.h"
#import "HDAddMyCommunity.h"
#import "HDAddNewCommunityController.h"
#import "HDChooseComView.h"
/** 删除我的小区*/
#import "SNDeleteCommunityManager.h"

static const CGFloat kCartTotalPanelHeight = 120;

@interface HDMyCommunityController ()<HDChooseComViewDelegate,HDMyCommunityDelegate,HDAddMyCommunityDelegate,MBProgressHUDDelegate>

@property (nonatomic,strong) HDCommunityManager * communityMangaer;
@property (nonatomic,strong) HDCommunityResult * communityResult;
@property (nonatomic,strong) HDCommunityResult * chooseComResult;
@property (nonatomic,strong) UITableView * communitytableView;
@property (strong,nonatomic) MBProgressHUD* progress_;
@property (nonatomic, strong) SNDeleteCommunityManager  * deleteCommunityManager;
@property (nonatomic, strong) SNDeleteCommunityResult   * deleteCommunityResult;
@property (nonatomic,strong) UIButton * backBtn;
/** add by sn*/
@property (nonatomic, strong) UIButton * addCommunityBtn;
/** add end*/

@end

@implementation HDMyCommunityController

-(void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"我的小区";
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBar.hidden = NO;
    
    _deleteCommunityManager = [SNDeleteCommunityManager shareManager];
    _deleteCommunityResult = [[SNDeleteCommunityResult alloc] initWithTarget:self action:@selector(deleteMyCommunityUrl:)];
    
    self.communitytableView = [[UITableView alloc]initWithFrame:CGRectOf(CGPointMake(0, 64),
                                                                [self.view.ubo fw:UB_WIDTH fh:UB_HEIGHT uh:-kCartTotalPanelHeight oh:-60]) style:UITableViewStyleGrouped];
    self.communitytableView.sectionHeaderHeight = self.communitytableView.sectionFooterHeight = 0;
    self.communitytableView.tableHeaderView = self.communitytableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.1)];
    self.communitytableView.headerRefreshController = [[UIRefreshHeaderController alloc] initWithTableView:self.communitytableView caller:[UBTargetCaller of:self action:@selector(refreshData)]];
    self.communitytableView.nothingRefreshView = [[UIRefreshNotingRefreshView alloc]initWithView:self.communitytableView viewController:self tryAgain:@selector(refreshData)];
    self.communitytableView.backgroundColor = [XCommon hexStringToColor:kColor_lightGray_cell];
    self.communitytableView.delegate = self;
    self.communitytableView.dataSource = self;
    [self.view addSubview:self.communitytableView];
    
    
    self.communityMangaer = [HDCommunityManager shareManager];
    self.communityResult = [[HDCommunityResult alloc]initWithTarget:self action:@selector(loadCommunityData:)];
    self.chooseComResult = [[HDCommunityResult alloc]initWithTarget:self action:@selector(chooseResult:)];
    
    
    self.addCommunityBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.addCommunityBtn.frame = CGRectOf([self.communitytableView.ufo fx:0 ox:15 fy:1.0 oy:10],
                                          [self.view.ubo ow:SCREEN_WIDTH - 30 oh:40]);
    UIImage * BGimage = [UIImage imageNamed:@"color.png"];
    CGFloat top = 6;
    CGFloat bottom = 6;
    CGFloat left = 6;
    CGFloat right = 6;
    UIEdgeInsets insets = UIEdgeInsetsMake(top, left, bottom, right);
    BGimage = [BGimage resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch];
    [self.addCommunityBtn setBackgroundImage:BGimage forState:UIControlStateNormal];
    [self.addCommunityBtn setTitle:@"添加我的小区" forState:UIControlStateNormal];
    [self.addCommunityBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.addCommunityBtn addTarget:self action:@selector(addMyCommunityOrNext) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.addCommunityBtn];
    
//    if (self.isFirstAdd.integerValue == 0) {
//        //重写返回按钮
//        self.backBtn = [[UIButton alloc] initWithFrame:CGRectOf([self.ubo fx:UB_LEFT fy:UB_TOP],
//                                                                [self.ubo ow:40 oh:40])];
//        [self.backBtn setImage:[UIImage imageNamed:kImageMallSearchGrayArrowBackReturn] forState:UIControlStateNormal];
//        self.backBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
//        [self.backBtn addTarget:self action:@selector(leftBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
//        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.backBtn];
//    }
    
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refreshData) name:@"addNewCommunity" object:nil];
    
    
}

- (void)addMyCommunityOrNext
{
    //跳转页面
    HDAddNewCommunityController * addNewComView = [[HDAddNewCommunityController alloc]init];
    addNewComView.isAddNew = YES;
    [self.navigationController pushViewController:addNewComView animated:YES];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
    
    if ([[NSUserDefaults standardUserDefaults]boolForKey:@"havenewcom"]) {
        [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"havenewcom"];
        [self resutlCommunityList];
        
    }else{
        if (![self.communityMangaer fmdbIncludeCommunity] || ![self.communityMangaer fmdbIncludeCommunityData]) {
            [self.communitytableView.nothingRefreshView show];
            [self resutlCommunityList];
        }else{
            
            if ([self.communityMangaer shouldRefreshCommunityData]) {
                [self resutlCommunityList];
            }else
            {
                self.communityResult.dataSourceArray = [self.communityMangaer arrayFromFmdb];
                
                [self.communitytableView reloadData];
            }
        }
    }
}

-(void)leftBarBtnClicked:(UIButton*)sender
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

#pragma mark - 发送请求
-(void)resutlCommunityList
{
    [self.communityMangaer loadCommunityData:self.communityResult Refresh:@"0"];
}

#pragma mark - 刷新
- (void)refreshData
{
     [self.communityMangaer loadCommunityData:self.communityResult Refresh:@"1"];
}

#pragma mark - 数据处理
-(void)loadCommunityData:(HDCommunityResult*)rt
{
    [self.communitytableView endRefreshingAll];
    
    if (rt.success) {
        [self.communitytableView.nothingRefreshView remove];
        
        if (rt.haveData == YES) {
            
            #pragma mark - 查看当前全局保存的小区名字和小区id有没有 避免以外操作,删除了当前选择的小区或者没有返回用户当前选择的小区 这两种情况.
            NSString * myAreaID = [[NSUserDefaults standardUserDefaults] objectForKey:kMyAreaID];
            if (!myAreaID || !myAreaID.length) {
                [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:kMyAreaID];
            }
            
            NSString * myAreaTitle = [[NSUserDefaults standardUserDefaults] objectForKey:kMyAreaTitle];
            if (!myAreaTitle || !myAreaTitle.length) {
                [[NSUserDefaults standardUserDefaults] setObject:@"双明汇" forKey:kMyAreaTitle];
            }
            
            #pragma mark - add end
            
            self.communityResult.dataSourceArray = [self.communityMangaer arrayFromFmdb];
            [self.communitytableView reloadData];
            
            
        }
        
    }else
    {
        [self.communitytableView.nothingRefreshView activeStop];
    }
    
}
#pragma mark - tableView代理
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    DLog(@" ======= %d",self.communityResult.dataSourceArray.count);
    return self.communityResult.dataSourceArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * cellIdentifier = @"cellIdentifier";
    HDMyCommunityCell * cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[HDMyCommunityCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    cell.delegate = self;
    HDMyCommunityModel * model = self.communityResult.dataSourceArray[[indexPath section]];
    if (model.delSign.integerValue == 000) {
        [cell cellWithModel:model Row:indexPath.row];
    }
    
    cell.backgroundView = nil;
    
    return cell;
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kHDMyCommunityCellH;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    HDMyCommunityModel * model = self.communityResult.dataSourceArray[[indexPath section]];
    HDChooseComView * chooseComView = [[HDChooseComView alloc]initWithChoose:model];
    chooseComView.delegate = self;
    [self.view addSubview:chooseComView];
}

#pragma mark - 删除我的小区 add by SN
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    HDMyCommunityModel * model = self.communityResult.dataSourceArray[[indexPath section]];
    
    if (model.selected.integerValue) {
        [MyToast showDefaultBottonWithText:@"不能删除当前选中的小区..."];
        return;
    }
    
    [MBProgressHUD showMBProgressHUBOnWindowsWithMessage:@"删除小区中..."];
    [_deleteCommunityManager deleteCommunityWithResult:_deleteCommunityResult houseID:model.house_id cmid:model.cmid];
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 0;
    }
    return 10;
}

#pragma mark - cellChooseDelegate
-(void)cellChooseWithButton:(HDChooseButton *)btn
{
    if (btn.tag == 1) {
        //选择小区
        [btn.superview removeFromSuperview];
        
        self.progress_ = [[MBProgressHUD alloc]initWithView:self.view];
        [self.view addSubview:self.progress_];
        [self.view bringSubviewToFront:self.progress_];
        self.progress_.delegate = self;
        [self.progress_ show:YES];
        
        NSDictionary * params = @{@"cmid":btn.cmid,
                                  @"id":btn.house_id};
//        [self.communityMangaer chooseCommunity:self.chooseComResult Params:params Com:btn.community];
        [self.communityMangaer chooseCommunity:self.chooseComResult Params:params Com:btn.house_name];
        
        
        
    }else if (btn.tag == 2){
        //取消
        [btn.superview removeFromSuperview];
        
    }
}

-(void)chooseResult:(HDCommunityResult*)rt
{
    if (self.progress_) {
        [self.progress_ removeFromSuperview];
        self.progress_ = nil;
    }
    if (rt.success) {
        
        
        NSArray *array = [rt.community_name componentsSeparatedByString:@","];
        
        NSString * house_name = [array objectAtIndex:0];
        
        [[NSUserDefaults standardUserDefaults] setObject:rt.house_id forKey:@"currentCom"];
        [[NSUserDefaults standardUserDefaults] setObject:house_name forKey:kMyAreaTitle];
        [[NSUserDefaults standardUserDefaults] setObject:rt.cmid forKey:kMyAreaID];
        [[NSUserDefaults standardUserDefaults] synchronize];
        self.communityResult.dataSourceArray = [self.communityMangaer arrayFromFmdb];
        [self.communitytableView reloadData];
        
    }
    
    
}

#pragma mark - 添加我的小区
-(void)addMyCommunityOrNext:(UIButton *)btn
{
    if (btn.tag == 1) {
       //跳转到添加小区界面
        //跳转页面
        HDAddNewCommunityController * addNewComView = [[HDAddNewCommunityController alloc]init];
        addNewComView.isAddNew = YES;
        [self.navigationController pushViewController:addNewComView animated:YES];
    }
    
}

#pragma mark - 删除我的小区的返回
- (void)deleteMyCommunityUrl:(SNDeleteCommunityResult *)result
{
    [MBProgressHUD dismissMBProgressHUBOnWindows];
    if (result.success) {
        [MyToast showDefaultBottonWithText:@"删除小区成功"];
        [self refreshData];
    } else {
        [MyToast showDefaultBottonWithText:@"删除小区失败,请重试..."];
    }
}

@end

